from django.db.models import F, Q, Sum
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
import json
from booktest.models import BookInfo, HeroInfo
"""
GET     /books/         提供所有记录
POST    /books/         新增一条记录
GET     /books/<pk>/    提供指定id的记录
PUT     /books/<pk>/    修改指定id的记录
DELETE  /books/<pk>/    删除指定id的记录

响应数据    JSON
"""


class BookListView(View):
    """列表视图：不带pk"""

    def get(self, request):
        """
        查询所有书籍
        路由：GET /books/
        """
        books = BookInfo.objects.all()

        book_list = []
        # 要把查询集中的模型对象转换成一个一个的字典
        for book in books:
            book_dict = {
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else ''
            }

            book_list.append(book_dict)
        # 注意返回的是一个列表 需要设置safe=False
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        # 除本身的数据不用验证，其他获取的数据在使用前必须校验
        # 把数据储存到表中
        book = BookInfo.objects.create(
            btitle=json_dict.get('btitle'),
            bpub_date=json_dict.get('bpub_date'),
        )
        # 把模型转成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }

        # 响应
        return JsonResponse(book_dict, status=201)


class BookDetailView(View):
    """详情视图，带pk"""
    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 把模型转成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }

        return JsonResponse(book_dict, status=200)

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # 获取到要修改的模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 修改模型对象
        book.btitle = json_dict['btitle']
        book.bpub_date = json_dict['bpub_date']
        book.bread = json_dict.get('bread', book.bread)
        book.save()

        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bcomment': book.bcomment,
            'bread': book.bread,
            'image': book.image.url if book.image else ''

        }

        return JsonResponse(book_dict, status=200)

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        book.delete()

        return HttpResponse(status=204)
